<?php

namespace App\Model\Stat;

use Hyperf\DbConnection\Db;
use Hyperf\DbConnection\Model\Model;

/**
 *  每日统计-主播收入等信息
 */
class StatDailyHostInfo extends Model
{
    protected $connection = 'stat';
    protected $table = 'stat_daily_host_info';
    protected $fillable = [
        'user_id', 'dt', 'income_gift', 'income_msg', 'income_voice', 'income_video', 'income_sysgift', 'video_answer_time', 'video_answer_num', 'success_rate', 'video_call_num', 'video_match_num', 'msg_back_rate', 'super_chat_num', 'receive_num', 'receive_user_num',

        'online_time', 'income_total', 'call_minutes', 'average_call_time', 'msg_back_num', 'income_video_default', 'income_video_match', 'income_video_invite', 'income_video_discount', 'income_video_daily_free', 'income_daily_task'
    ];

    /**
     * 详情类型
     */
    const DETAIL_TYPE = [
//        'total_income' => ['累计收益', '金币'],
        'income_total' => ['当日收益', '金币'],
        'week_income' => ['周收益', '金币'],
        'online_time' => ['在线时长', ''],
        'call_minutes' => ['通话时长', ''],
        'average_call_time' => ['平均通话', '分钟'],
        'super_chat_num' => ['互动人数', ''],
    ];

    static function getData($userId = 0, $date = '')
    {
        $date = $date ?: date('Y-m-d');
        $where = [
            'user_id' => $userId,
            'dt' => $date,
        ];
        $data = self::where($where)->first();
        return $data ? $data->toArray() : [];
    }

    /**
     * 按呼叫时长获取主播列表
     */
    static function getCallRankList($num = 10, $start = '', $end = '')
    {
        $where = [
            ['dt', '>=', $start]
        ];
        $end && $where[] = ['dt', '<=', $end];
        $data = self::where($where)->select(['user_id', Db::raw('SUM(call_minutes) as call_minutes')])->groupBy('user_id')->orderBy('call_minutes', 'desc')->limit($num)->get()->toArray();
        return $data;
    }

    /**
     * 按呼叫时长获取主播列表
     */
    static function getCallData($userId = 0, $start = '', $end = '')
    {
        $where = [
            ['user_id', $userId],
            ['dt', '>=', $start]
        ];
        $end && $where[] = ['dt', '<=', $end];
        $data = self::where($where)->select([Db::raw('SUM(call_minutes) as call_minutes')])->first();
        return $data && $data->call_minutes ? $data->call_minutes : 0;
    }

    /**
     * 获取时间范围收入和
     */
    static function getIncomeData($userId = 0, $start = '', $end = '')
    {
        $where = [
            ['user_id', $userId],
            ['dt', '>=', $start]
        ];
        $end && $where[] = ['dt', '<=', $end];
        $data = self::where($where)->select([Db::raw('SUM(income_total) as value')])->first();
        return $data && $data->value ? $data->value : 0;
    }

    /**
     * 活跃主播
     */
    static function getActiveHosts($date = '')
    {
        $date = $date ?: date('Y-m-d');
        $where = ['dt' => $date];
        return self::where($where)->pluck('user_id')->toArray();
    }
}
